/**
 * Function creates the initial map and wfs layers. On search, the function updates the
 * wfs layer accordingly (creates new filter with given search terms etc.).
 */
function ladattu() {
  var wms_url = document.URL + 'map/wms?',
  wfs_url = document.URL + 'map/wfs?',
  search,
  lon,
  lat,
  radius,
  baseLayer = 0,		
  point,
  filter2,
  areaControl,
  search_property = "pnr:nimi/pnr:PaikanNimi/pnr:kirjoitusasu",
  feature_type = "pnr:Paikka",
  layers = new WMS().createWMSLayers(wms_url),		
  map = createMap(wms_url),
  municipalityLayer = new OpenLayers.Layer.WMS("Kuntarajat 1:4500", wms_url,
  {
    layers: 'kuntarajat_4500k', 
    transparent: true
  },

  {
    isBaseLayer: false, 
    opacity: 0,
    maxExtent: new OpenLayers.Bounds(54199.4814, 6595573.2276023, 748199.4814, 7781573.2276023)
  }
  ),
  municipalities = [],
  munis = new setJSONdata('municipalities'),
  activeLayer = 0,
  style_map = new Style().createStyleMap(3, map),
  wfs = new WFS().createWFSLayer(style_map);

  map.addLayers(layers);
  map.addLayer(municipalityLayer);
  map.addLayer(wfs);
  map.zoomToMaxExtent();
  addClickActions(map, wfs, wfs_url);

  /**
   * Creates the OpenLayers map for the application.
   *
	 * @param {string} wms_url url for the wms service
	 * @returns map layer
	 */
  function createMap(wms_url) {
    var map = new OpenLayers.Map('map', {
      div: 'map',
      controls:[ new OpenLayers.Control.ZoomPanel(), new OpenLayers.Control.Navigation() ],
      maxResolution: 2000,
      projection: "EPSG:3067",
      numZoomLevels:layers.length
    });
    return map;
  }

  /**
	 * Function changes the current shown layer to one
   * with a greater resolution.
	 */
  zoomIn = function() {
    if( baseLayer < layers.length ) {
      map.setBaseLayer(layers[++baseLayer]);
    }
    console.log("+ " + baseLayer);
  }

  /**
   * Function changes the current shown layer to one
   * with the least resolution.
   */
  zoomToMaxExtent = function() {
    baseLayer = 0;
    map.setBaseLayer(layers[baseLayer]);
    console.log(baseLayer);
  }
	
  /**
   * Function changes the current shown layer to one
   * with a lesser resolution.
   */
  zoomOut = function() {
    if( baseLayer >= 0 ) {
      map.setBaseLayer(layers[--baseLayer]);
    }
    console.log("- " + baseLayer);
  }

  /**
   * If the search field is not empty, executes a search for the search term.
   * If radial search is configured and set, an additional filter is added to the
   * search.
   *
   * @param {string} search_term The search term to be used for search
   */
  doSearch = function(search_term) {
    lat = $("#latBox").val();
    lon = $("#lonBox").val();
    radius = $("#radiusBox").val();

    if (search_term.length != 0 && lon.length != 0 &&
      lat.length != 0 && radius.length != 0) {
      point = new OpenLayers.Geometry.Point(lon, lat);
      filter = new Filters().createFilter(search_property, search_term);
      filter2 = new Filters().createRadialFilter(point, radius);
      filter = new Filters().createAndFilter(filter, filter2);
      new WFS().updateMap(map, wfs, wfs_url, filter, feature_type);
    }
    else if (search_term.length != 0) {
      filter = new Filters().createFilter(search_property, search_term);
      new WFS().updateMap(map, wfs, wfs_url, filter, feature_type);
    }
  }

  // On hitting return, the function updates the map according to search terms.
  $("#searchBox").keypress(function (event) {
    if (event.keyCode === 13) {
      doSearch($("#searchBox").val());
    }
  });
	
  // Hitting return on any of the items in the autocomplete drop down list updates the map
  $("#searchBox").autocomplete({
    source: "locations/search.json",
    minLength: 3,
    select: function(event, data) {
      doSearch(data.item.value);
    }
  });

  // Populate array for municipality search autocomplete
  $.each(munis, function(i) {
    if (munis[i] !== undefined) {
      municipalities.push(munis[i].fin);
    }
  });
  $("#municipalityBox").autocomplete({
    source: municipalities,
    minLength: 3
  });

  // On clicking the checkbox the municipality layer is either displayed or hidden.
  $("#showMunicipality").change(function () {
    if (municipalityLayer.opacity === 0) {
      municipalityLayer.setOpacity(0.75);
    }
    else {
      municipalityLayer.setOpacity(0);
    }
  });

	// jätetään vain infosivu aluksi näkyviin.
	$("#results").hide();
	$("#searchoptions").hide();
	$("#infolink").addClass('activebutton');
	
	// divejen vaihto
	$("#infolink").click( function() {
	    $(".navibutton").removeClass('activebutton');
	    $("#infolink").addClass('activebutton');
		$("#info").show();
		$("#results").hide();
		$("#searchoptions").hide();
	});
	
	$("#resultslink").click( function() {
	    $(".navibutton").removeClass('activebutton');
	    $("#resultslink").addClass('activebutton');
		$("#results").show();
		$("#info").hide();
		$("#searchoptions").hide();
	});
	
	$("#searchlink").click( function() {
	    $(".navibutton").removeClass('activebutton');
	    $("#searchlink").addClass('activebutton');
		$("#searchoptions").show();
		$("#results").hide();
		$("#info").hide();
	});		

  $("#listView").hide();
  $("#toggleListButton").click( function () {
    new WFS().changeListView();
  });
	
  $(".olControlZoomInItemInactive").click( function() {
    zoomIn()
  });
	
  $(".olControlZoomToMaxExtentItemInactive").click( function() {
    zoomToMaxExtent()
  });
	
  $(".olControlZoomOutItemInactive").click( function() {
    zoomOut()
  });
	
  $("#map").dblclick( function() { 	
    zoomIn();
    if(map.getZoom() != baseLayer)
    	map.zoomIn();		
  });

  new WFS().populateLocationTypeSelection();
  
  //Add print button functinality
  $("#printButton").click(function(){print();});
  $("#csvButton").click(function(){featuresToCSV();});
  //Array to hold our features for csv creation.
  //TODO: get rid of fugly global variable.
  //Currently as is because it get randomly reinitialized
  //if defined in class...
}

$(ladattu);